from django.shortcuts import render
from django.http import HttpResponse
from myadmin import models
from django.core.paginator import Paginator
from django.db.models import Q

# Create your views here.

# 前台 - 首页
def index(request):
    # 全部图书对象
    googsdata = models.Books.objects.all()
    # 畅销榜图书类别
    w_f = models.BookType.objects.get(id=43)

    context = {'classify':getNavData(),'googsdata':googsdata,'w_f':w_f}
    return render(request,'myhome/index.html',context)


# 前台 - 类别页面
def category(request,cid):
    # 获取分类id，查询分类对象
    classifyobj = models.BookType.objects.get(id=cid)

    # 判断当前分类是否为顶级分类
    if classifyobj.pid == 0 :
        # 获取顶级分类下的一级子类
        sub = models.BookType.objects.filter(pid=classifyobj.id)
        googlist = []
        for i in sub:
            for ii in i.books_set.all() :
                googlist.append(ii)
        data = {'parent':classifyobj,'sub':sub,'googlist':googlist}
    else:
        # 获取一级分类所属的顶级分类
        parentobj = models.BookType.objects.get(id=classifyobj.pid)
        # 获取该顶级分类下的所有一级子类
        sub = models.BookType.objects.filter(pid=classifyobj.pid)
        googlist = classifyobj.books_set.all()
        data = {'parent':parentobj,'sub':sub,'googlist':googlist,'obj':classifyobj}

    # 创建分页对象
    p = Paginator(googlist,20)
    # 获取点击的页码
    page_index = request.GET.get('page',1)
    # 根据页码获取需要展示的数据
    googlist = p.page(page_index)
    data['googlist'] = googlist

    # 畅销榜图书类别
    w_f = models.BookType.objects.get(id=43)
    context = {'classify':getNavData(),'classifyobj':data,'w_f':w_f}
    return render(request,'myhome/category.html',context)


# 前台 - 商品详情
def bookdetails(request,bid):
    try:
        # 获取当前图书对象
        bookobj = models.Books.objects.get(id=bid)
        context = {'classify':getNavData(),'bookobj':bookobj}
        return render(request,'myhome/bookdetails.html',context)
    except:
        return HttpResponse('<script>alert("没有找到图书数据");history.back();</script>')


#  前台 - 搜索结果
def search(request):
    data = models.Books.objects.all()
    keywords = request.GET.get('keywords',None)
    data = data.filter(Q(title__contains=keywords)|Q(author__contains=keywords))

    w_f = models.BookType.objects.get(id=43)
    context = {'classify':getNavData(),'data':data,'w_f':w_f}
    return render(request,'myhome/search.html',context)


# 封装函数，获取导航分类
def getNavData():
    # 获取所有顶级分类
    classify = models.BookType.objects.filter(pid=0)
    for i in classify:
        # 在顶级分类中定义属性sub，并获取各个顶级分类下的一级子类
        i.sub = models.BookType.objects.filter(pid=i.id)

    return classify


